<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="课程名称" prop="courseName">
        <el-input
          v-model="queryParams.courseName"
          placeholder="请输入课程名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="请选择状态" clearable>
          <el-option label="正常" value="0" />
          <el-option label="停用" value="1" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
        >删除</el-button>
      </el-col>
<!--      <el-col :span="1.5">-->
<!--        <el-button-->
<!--          type="info"-->
<!--          plain-->
<!--          icon="el-icon-video-camera"-->
<!--          size="mini"-->
<!--          @click="handleUpload"-->
<!--        >上传课程</el-button>-->
<!--      </el-col>-->
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="courseList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="课程ID" align="center" prop="courseId" width="80" />
      <el-table-column label="封面" align="center" width="120">
        <template slot-scope="scope">
          <el-image
            v-if="scope.row.coverUrl"
            :src="scope.row.coverUrl"
            :preview-src-list="[scope.row.coverUrl]"
            fit="cover"
            style="width: 100px; height: 56px; border-radius: 4px;"
          />
          <span v-else style="color: #909399;">暂无封面</span>
        </template>
      </el-table-column>
      <el-table-column label="课程名称" align="center" prop="courseName" :show-overflow-tooltip="true" min-width="200" />
      <el-table-column label="课程简介" align="center" prop="courseDesc" :show-overflow-tooltip="true" min-width="250" />
      <el-table-column label="状态" align="center" prop="status" width="80">
        <template slot-scope="scope">
          <el-tag :type="scope.row.status === '0' ? 'success' : 'danger'">
            {{ scope.row.status === '0' ? '正常' : '停用' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="观看数" align="center" prop="viewCount" width="90" />
      <el-table-column label="点赞数" align="center" prop="likeCount" width="90" />
      <el-table-column label="收藏数" align="center" prop="collectCount" width="90" />
      <el-table-column label="评论数" align="center" prop="commentCount" width="90" />
      <el-table-column label="创建时间" align="center" prop="createTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createTime, '{y}-{m}-{d} {h}:{i}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" width="200" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改课程对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="1400px" append-to-body>
      <div class="dialog-content-wrapper">
        <div class="dialog-content">
          <!-- 第一部分：课程基本信息 -->
          <h2 class="section-title">课程基本信息</h2>
          <el-form ref="courseFormRef" :model="form" :rules="rules" label-width="100px" class="section-form">
            <el-form-item label="课程名称" prop="courseName">
              <el-input v-model="form.courseName" placeholder="请输入课程名称" />
            </el-form-item>
            <el-form-item label="课程简介" prop="courseDesc">
              <el-input v-model="form.courseDesc" type="textarea" :rows="4" placeholder="请输入课程简介" />
            </el-form-item>
            <el-form-item label="课程封面">
              <el-upload
                :action="uploadBase + '/admin/video/upload-course-cover'"
                :headers="uploadHeaders"
                :data="{ courseId: form.courseId }"
                :disabled="!form.courseId"
                :show-file-list="false"
                :on-success="onCourseCoverSuccess"
                :before-upload="beforeCourseCoverUpload"
              >
                <el-button type="primary" :disabled="!form.courseId">上传课程封面</el-button>
              </el-upload>
              <div v-if="form.coverUrl" class="preview" style="margin-top: 10px;">
                <el-image
                  :src="form.coverUrl"
                  style="width: 200px; height: 112px; border-radius: 4px;"
                  fit="cover"
                />
              </div>
              <div v-if="!form.courseId" class="tip" style="color: #909399; margin-top: 6px;">请先保存课程基本信息后再上传封面</div>
            </el-form-item>
            <el-form-item label="分类ID" prop="categoryId">
              <el-input-number v-model="form.categoryId" :min="1" placeholder="请输入分类ID" />
            </el-form-item>
            <el-form-item label="状态" prop="status">
              <el-radio-group v-model="form.status">
                <el-radio label="0">正常</el-radio>
                <el-radio label="1">停用</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-form>

          <!-- 第二部分：视频集管理 -->
          <h2 class="section-title">视频集管理</h2>
          <div class="section-content">
            <div class="toolbar" style="margin-bottom: 12px;">
              <el-button type="primary" @click="openEpisodeDialog" :disabled="!form.courseId">新增视频集</el-button>
            </div>
            <el-table :data="episodes" border stripe>
              <el-table-column type="index" label="#" width="50" />
              <el-table-column prop="episodeTitle" label="名称" min-width="160" />
              <el-table-column prop="episodeDesc" label="简介" min-width="200" />
              <el-table-column prop="episodeNumber" label="集数" width="80" />
              <el-table-column prop="sort" label="排序" width="80" />
              <el-table-column prop="duration" label="时长(秒)" width="100" />
              <el-table-column label="状态" width="80">
                <template slot-scope="scope">
                  <el-tag :type="scope.row.status === '0' ? 'success' : 'danger'">
                    {{ scope.row.status === '0' ? '正常' : '停用' }}
                  </el-tag>
                </template>
              </el-table-column>
              <el-table-column label="课程视频" min-width="220">
                <template slot-scope="{ row }">
                  <div class="row-upload">
                    <el-upload
                      :action="uploadBase + '/admin/video/upload-course-video'"
                      :headers="uploadHeaders"
                      :data="{ courseId: form.courseId, episodeId: row.episodeId }"
                      :show-file-list="false"
                      :disabled="!row.episodeId"
                      :on-success="(res)=>onEpisodeVideoSuccess(res, row)"
                      :before-upload="beforeEpisodeVideoUpload"
                    >
                      <el-button type="primary" size="mini" :disabled="!row.episodeId">上传视频</el-button>
                    </el-upload>
                    <a v-if="row.videoUrl" :href="row.videoUrl" target="_blank" style="margin-left: 10px;">预览</a>
                  </div>
                </template>
              </el-table-column>
              <el-table-column label="封面" min-width="220">
                <template slot-scope="{ row }">
                  <div class="row-upload">
                    <el-upload
                      :action="uploadBase + '/admin/video/upload-episode-cover'"
                      :headers="uploadHeaders"
                      :data="{ courseId: form.courseId, episodeId: row.episodeId }"
                      :show-file-list="false"
                      :disabled="!row.episodeId"
                      :on-success="(res)=>onEpisodeCoverSuccess(res, row)"
                      :before-upload="beforeEpisodeCoverUpload"
                    >
                      <el-button size="mini" :disabled="!row.episodeId">上传封面</el-button>
                    </el-upload>
                    <img v-if="row.coverUrl" :src="row.coverUrl" class="thumb" />
                  </div>
                </template>
              </el-table-column>
              <el-table-column label="操作" width="150" fixed="right">
                <template slot-scope="scope">
                  <el-button size="mini" type="text" icon="el-icon-edit" @click="handleEditEpisode(scope.row)">编辑</el-button>
                  <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDeleteEpisode(scope.row)">删除</el-button>
                </template>
              </el-table-column>
            </el-table>
          </div>

          <!-- 第三部分：分解动作管理 -->
          <h2 class="section-title">分解动作管理</h2>
          <div class="section-content">
            <div class="toolbar" style="margin-bottom: 12px;">
              <el-select v-model="selectedEpisodeId" placeholder="选择视频集" style="width: 260px; margin-right: 10px;" @change="loadActionsByEpisode">
                <el-option v-for="ep in episodes" :key="ep.episodeId" :label="ep.episodeTitle" :value="ep.episodeId" />
              </el-select>
              <el-button type="primary" @click="openActionDialog" :disabled="!selectedEpisodeId">新增分解动作</el-button>
            </div>
            <el-table :data="actions" border stripe>
              <el-table-column type="index" label="#" width="50" />
              <el-table-column prop="actionTitle" label="名称" min-width="160" />
              <el-table-column prop="actionDesc" label="简介" min-width="200" />
              <el-table-column prop="startTime" label="开始时间(秒)" width="120" />
              <el-table-column prop="endTime" label="结束时间(秒)" width="120" />
              <el-table-column prop="sort" label="排序" width="80" />
              <el-table-column label="状态" width="80">
                <template slot-scope="scope">
                  <el-tag :type="scope.row.status === '0' ? 'success' : 'danger'">
                    {{ scope.row.status === '0' ? '正常' : '停用' }}
                  </el-tag>
                </template>
              </el-table-column>
              <el-table-column label="动作视频" min-width="220">
                <template slot-scope="{ row }">
                  <div class="row-upload">
                    <el-upload
                      :action="uploadBase + '/admin/video/upload-action-video'"
                      :headers="uploadHeaders"
                      :data="{ courseId: form.courseId, episodeId: selectedEpisodeId, actionId: row.actionId }"
                      :show-file-list="false"
                      :disabled="!row.actionId"
                      :on-success="(res)=>onActionVideoSuccess(res, row)"
                      :before-upload="beforeActionVideoUpload"
                    >
                      <el-button type="primary" size="mini" :disabled="!row.actionId">上传视频</el-button>
                    </el-upload>
                    <a v-if="row.videoUrl" :href="row.videoUrl" target="_blank" style="margin-left: 10px;">预览</a>
                  </div>
                </template>
              </el-table-column>
              <el-table-column label="封面" min-width="220">
                <template slot-scope="{ row }">
                  <div class="row-upload">
                    <el-upload
                      :action="uploadBase + '/admin/video/upload-course-cover'"
                      :headers="uploadHeaders"
                      :data="{ courseId: form.courseId, episodeId: selectedEpisodeId, actionId: row.actionId }"
                      :show-file-list="false"
                      :disabled="!row.actionId"
                      :on-success="(res)=>onActionCoverSuccess(res, row)"
                      :before-upload="beforeActionCoverUpload"
                    >
                      <el-button size="mini" :disabled="!row.actionId">上传封面</el-button>
                    </el-upload>
                    <img v-if="row.coverUrl" :src="row.coverUrl" class="thumb" />
                  </div>
                </template>
              </el-table-column>
              <el-table-column label="操作" width="150" fixed="right">
                <template slot-scope="scope">
                  <el-button size="mini" type="text" icon="el-icon-edit" @click="handleEditAction(scope.row)">编辑</el-button>
                  <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDeleteAction(scope.row)">删除</el-button>
                </template>
              </el-table-column>
            </el-table>
          </div>
        </div>
      </div>

      <!-- 视频集编辑弹框 -->
      <el-dialog title="视频集信息" :visible.sync="episodeDialogVisible" width="700px" append-to-body>
        <el-form ref="episodeFormRef" :model="episodeForm" :rules="episodeRules" label-width="100px">
          <el-form-item label="视频集标题" prop="episodeTitle">
            <el-input v-model="episodeForm.episodeTitle" placeholder="请输入视频集标题" />
          </el-form-item>
          <el-form-item label="视频集简介">
            <el-input v-model="episodeForm.episodeDesc" type="textarea" :rows="3" placeholder="请输入视频集简介" />
          </el-form-item>
          <el-form-item label="集数">
            <el-input-number v-model="episodeForm.episodeNumber" :min="1" />
          </el-form-item>
          <el-form-item label="排序">
            <el-input-number v-model="episodeForm.sort" :min="0" />
          </el-form-item>
          <el-form-item label="状态">
            <el-radio-group v-model="episodeForm.status">
              <el-radio label="0">正常</el-radio>
              <el-radio label="1">停用</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="视频">
            <el-upload
              :action="uploadBase + '/admin/video/upload-course-video'"
              :headers="uploadHeaders"
              :data="{ courseId: form.courseId, episodeId: episodeForm.episodeId }"
              :show-file-list="false"
              :disabled="!episodeForm.episodeId"
              :on-success="onEpisodeDialogVideoSuccess"
              :before-upload="beforeEpisodeVideoUpload"
            >
              <el-button type="primary" :disabled="!episodeForm.episodeId">上传视频</el-button>
            </el-upload>
            <div v-if="episodeForm.videoUrl" style="margin-top: 10px;">
              <a :href="episodeForm.videoUrl" target="_blank" style="color: #409EFF;">预览视频</a>
            </div>
            <div v-if="!episodeForm.episodeId" class="tip" style="color: #909399; margin-top: 6px;">请先保存视频集基本信息后再上传视频</div>
          </el-form-item>
          <el-form-item label="封面">
            <el-upload
              :action="uploadBase + '/admin/video/upload-episode-cover'"
              :headers="uploadHeaders"
              :data="{ courseId: form.courseId, episodeId: episodeForm.episodeId }"
              :show-file-list="false"
              :disabled="!episodeForm.episodeId"
              :on-success="onEpisodeDialogCoverSuccess"
              :before-upload="beforeEpisodeCoverUpload"
            >
              <el-button :disabled="!episodeForm.episodeId">上传封面</el-button>
            </el-upload>
            <div v-if="episodeForm.coverUrl" style="margin-top: 10px;">
              <img :src="episodeForm.coverUrl" class="thumb" />
            </div>
            <div v-if="!episodeForm.episodeId" class="tip" style="color: #909399; margin-top: 6px;">请先保存视频集基本信息后再上传封面</div>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="episodeDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="submitEpisodeForm">确 定</el-button>
        </div>
      </el-dialog>

      <!-- 动作编辑弹框 -->
      <el-dialog title="分解动作信息" :visible.sync="actionDialogVisible" width="600px" append-to-body>
        <el-form ref="actionFormRef" :model="actionForm" :rules="actionRules" label-width="100px">
          <el-form-item label="动作标题" prop="actionTitle">
            <el-input v-model="actionForm.actionTitle" placeholder="请输入动作标题" />
          </el-form-item>
          <el-form-item label="动作描述">
            <el-input v-model="actionForm.actionDesc" type="textarea" :rows="3" placeholder="请输入动作描述" />
          </el-form-item>
          <el-form-item label="开始时间(秒)" prop="startTime">
            <el-input-number v-model="actionForm.startTime" :min="0" />
          </el-form-item>
          <el-form-item label="结束时间(秒)" prop="endTime">
            <el-input-number v-model="actionForm.endTime" :min="0" />
          </el-form-item>
          <el-form-item label="排序">
            <el-input-number v-model="actionForm.sort" :min="0" />
          </el-form-item>
          <el-form-item label="状态">
            <el-radio-group v-model="actionForm.status">
              <el-radio label="0">正常</el-radio>
              <el-radio label="1">停用</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="actionDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="submitActionForm">确 定</el-button>
        </div>
      </el-dialog>

      <div slot="footer" class="dialog-footer">
        <el-button @click="cancel">取 消</el-button>
        <el-button type="primary" @click="submitForm">保存课程信息</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { getToken } from '@/utils/auth'
import { listCourse, getCourse, delCourse, createCourse, updateCourse } from "@/api/video/course"
import { addEpisode, listEpisodeByCourse, updateEpisode, delEpisode } from "@/api/video/episode"
import { createAction, listActionByEpisode, updateAction, delAction } from "@/api/video/action"

export default {
  name: "Course",
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 课程表格数据
      courseList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 上传基础路径
      uploadBase: process.env.VUE_APP_BASE_API || '',
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        courseName: null,
        status: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        courseName: [
          { required: true, message: "课程名称不能为空", trigger: "blur" }
        ],
      },
      // 视频集相关
      episodes: [],
      episodeDialogVisible: false,
      episodeForm: {
        episodeId: null,
        episodeTitle: '',
        episodeDesc: '',
        episodeNumber: null,
        sort: 0,
        status: '0',
        videoUrl: '',
        coverUrl: ''
      },
      episodeRules: {
        episodeTitle: [
          { required: true, message: "视频集标题不能为空", trigger: "blur" }
        ]
      },
      // 动作相关
      selectedEpisodeId: null,
      actions: [],
      actionDialogVisible: false,
      actionForm: {
        actionId: null,
        actionTitle: '',
        actionDesc: '',
        startTime: null,
        endTime: null,
        sort: 0,
        status: '0'
      },
      actionRules: {
        actionTitle: [
          { required: true, message: "动作标题不能为空", trigger: "blur" }
        ],
        startTime: [
          { required: true, message: "开始时间不能为空", trigger: "blur" }
        ],
        endTime: [
          { required: true, message: "结束时间不能为空", trigger: "blur" }
        ]
      }
    }
  },
  computed: {
    uploadHeaders() {
      const token = getToken()
      return token ? { Authorization: 'Bearer ' + token } : {}
    }
  },
  created() {
    this.getList()
  },
  methods: {
    /** 查询课程列表 */
    getList() {
      this.loading = true
      listCourse(this.queryParams).then(response => {
        this.courseList = response.rows
        this.total = response.total
        this.loading = false
      })
    },
    // 取消按钮
    cancel() {
      this.open = false
      this.reset()
    },
    // 表单重置
    reset() {
      this.form = {
        courseId: null,
        courseName: null,
        courseDesc: null,
        coverUrl: null,
        categoryId: null,
        status: "0",
        viewCount: 0,
        likeCount: 0,
        collectCount: 0,
        commentCount: 0
      }
      this.episodes = []
      this.actions = []
      this.selectedEpisodeId = null
      this.resetForm("courseFormRef")
      this.resetForm("episodeFormRef")
      this.resetForm("actionFormRef")
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm")
      this.handleQuery()
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.courseId)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset()
      this.open = true
      this.title = "添加课程"
    },
    /** 上传课程按钮操作 */
    // handleUpload() {
    //   this.$router.push({ path: '/video/upload' })
    // },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset()
      const courseId = row.courseId || this.ids[0]
      getCourse(courseId).then(response => {
        // 后端返回的可能是 VO 对象，需要适配
        const data = response.data || response
        this.form = {
          courseId: data.courseId,
          courseName: data.courseName,
          courseDesc: data.courseDesc,
          coverUrl: data.coverUrl,
          categoryId: data.categoryId,
          status: data.status || "0",
          viewCount: data.viewCount || 0,
          likeCount: data.likeCount || 0,
          collectCount: data.collectCount || 0,
          commentCount: data.commentCount || 0
        }
        this.open = true
        this.title = "修改课程"
        // 加载视频集列表
        this.loadEpisodes(courseId)
      })
    },
    /** 提交按钮 */
    submitForm() {
      // 只验证课程基本信息表单（必填）
      this.$refs["courseFormRef"].validate(valid => {
        if (valid) {
          if (this.form.courseId != null) {
            // 修改课程
            updateCourse(this.form).then(response => {
              this.$modal.msgSuccess("修改成功")
              // 加载视频集列表
              this.loadEpisodes(this.form.courseId)
              this.getList()
            })
          } else {
            // 新增课程
            createCourse(this.form).then(response => {
              const res = response.data || response
              const courseId = res.courseId || (res.data && res.data.courseId)
              if (courseId) {
                this.form.courseId = courseId
                // 加载视频集列表
                this.loadEpisodes(courseId)
                this.$modal.msgSuccess("新增成功，请继续添加视频集和动作")
              } else {
                this.$modal.msgSuccess("新增成功")
                this.open = false
                this.getList()
              }
            })
          }
        }
      })
      // 注意：视频集和分解动作是可选的，不在这里验证和保存
      // 它们通过各自的弹框单独保存
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const courseIds = row ? [row.courseId] : this.ids
      this.$modal.confirm('是否确认删除课程编号为"' + courseIds.join(',') + '"的数据项？').then(() => {
        return delCourse(courseIds)
      }).then(() => {
        this.getList()
        this.$modal.msgSuccess("删除成功")
      }).catch(() => {})
    },
    // ========== 上传相关方法 ==========
    beforeCourseCoverUpload(file) {
      const isLt10M = file.size / 1024 / 1024 < 10
      if (!isLt10M) this.$message.error('封面大小不能超过 10MB!')
      if (!this.form.courseId) this.$message.warning('请先保存课程基本信息')
      return isLt10M && !!this.form.courseId
    },
    onCourseCoverSuccess(res) {
      if (res && (res.code === 200 || res.code === 0 || res.success)) {
        const url = (res.data && res.data.url) || res.url
        this.form.coverUrl = url
        this.$message.success('上传成功')
      } else {
        this.$message.error(res.msg || '上传失败')
      }
    },
    beforeEpisodeVideoUpload(file) {
      const ok = file.size < 1024 * 1024 * 1024
      if (!ok) this.$message.error('课程视频不能超过 1GB!')
      return ok
    },
    onEpisodeVideoSuccess(res, row) {
      if (res && (res.code === 200 || res.code === 0 || res.success)) {
        const url = (res.data && res.data.url) || res.url
        row.videoUrl = url
        this.$message.success('上传成功')
      } else {
        this.$message.error(res.msg || '上传失败')
      }
    },
    beforeEpisodeCoverUpload(file) {
      const ok = file.size < 5 * 1024 * 1024
      if (!ok) this.$message.error('视频集封面不能超过 5MB!')
      return ok
    },
    onEpisodeCoverSuccess(res, row) {
      if (res && (res.code === 200 || res.code === 0 || res.success)) {
        const url = (res.data && res.data.url) || res.url
        row.coverUrl = url
        this.$message.success('上传成功')
      } else {
        this.$message.error(res.msg || '上传失败')
      }
    },
    // 视频集弹框中的上传成功回调
    onEpisodeDialogVideoSuccess(res) {
      if (res && (res.code === 200 || res.code === 0 || res.success)) {
        const url = (res.data && res.data.url) || res.url
        this.episodeForm.videoUrl = url
        this.$message.success('视频上传成功')
      } else {
        this.$message.error(res.msg || '上传失败')
      }
    },
    onEpisodeDialogCoverSuccess(res) {
      if (res && (res.code === 200 || res.code === 0 || res.success)) {
        const url = (res.data && res.data.url) || res.url
        this.episodeForm.coverUrl = url
        this.$message.success('封面上传成功')
      } else {
        this.$message.error(res.msg || '上传失败')
      }
    },
    beforeActionVideoUpload(file) {
      const ok = file.size < 512 * 1024 * 1024
      if (!ok) this.$message.error('动作视频不能超过 512MB!')
      return ok
    },
    onActionVideoSuccess(res, row) {
      if (res && (res.code === 200 || res.code === 0 || res.success)) {
        const url = (res.data && res.data.url) || res.url
        row.videoUrl = url
        this.$message.success('上传成功')
      } else {
        this.$message.error(res.msg || '上传失败')
      }
    },
    beforeActionCoverUpload(file) {
      const ok = file.size < 5 * 1024 * 1024
      if (!ok) this.$message.error('动作封面不能超过 5MB!')
      return ok
    },
    onActionCoverSuccess(res, row) {
      if (res && (res.code === 200 || res.code === 0 || res.success)) {
        const url = (res.data && res.data.url) || res.url
        row.coverUrl = url
        this.$message.success('上传成功')
      } else {
        this.$message.error(res.msg || '上传失败')
      }
    },
    // ========== 视频集管理方法 ==========
    loadEpisodes(courseId) {
      if (!courseId) return
      listEpisodeByCourse(courseId).then(response => {
        const res = response.data || response
        if (res && (res.code === 200 || res.code === 0 || res.success)) {
          this.episodes = res.data || res || []
        } else {
          this.episodes = []
        }
      }).catch(() => {
        this.episodes = []
      })
    },
    openEpisodeDialog() {
      if (!this.form.courseId) {
        this.$message.warning('请先保存课程基本信息')
        return
      }
      this.episodeForm = {
        episodeId: null,
        episodeTitle: '',
        episodeDesc: '',
        episodeNumber: null,
        sort: 0,
        status: '0',
        videoUrl: '',
        coverUrl: ''
      }
      this.episodeDialogVisible = true
    },
    handleEditEpisode(row) {
      this.episodeForm = {
        episodeId: row.episodeId,
        episodeTitle: row.episodeTitle,
        episodeDesc: row.episodeDesc || '',
        episodeNumber: row.episodeNumber,
        sort: row.sort || 0,
        status: row.status || '0',
        videoUrl: row.videoUrl || '',
        coverUrl: row.coverUrl || ''
      }
      this.episodeDialogVisible = true
    },
    submitEpisodeForm() {
      this.$refs.episodeFormRef.validate(valid => {
        if (!valid) return
        const payload = {
          courseId: this.form.courseId,
          episodeTitle: this.episodeForm.episodeTitle,
          episodeDesc: this.episodeForm.episodeDesc,
          episodeNumber: this.episodeForm.episodeNumber,
          sort: this.episodeForm.sort,
          status: this.episodeForm.status
        }
        // 如果有视频URL和封面URL，也一起提交
        if (this.episodeForm.videoUrl) {
          payload.videoUrl = this.episodeForm.videoUrl
        }
        if (this.episodeForm.coverUrl) {
          payload.coverUrl = this.episodeForm.coverUrl
        }
        if (this.episodeForm.episodeId) {
          payload.episodeId = this.episodeForm.episodeId
          updateEpisode(payload).then(response => {
            this.$message.success('更新成功')
            this.episodeDialogVisible = false
            this.loadEpisodes(this.form.courseId)
          })
        } else {
          addEpisode(payload).then(response => {
            const res = response.data || response
            if (res && (res.code === 200 || res.code === 0 || res.success)) {
              // 获取返回的episodeId，用于后续上传
              const episodeId = (res.data && res.data.episodeId) || res.episodeId
              if (episodeId) {
                this.episodeForm.episodeId = episodeId
                this.$message.success('新增成功，可以继续上传视频和封面')
                // 刷新列表以显示新添加的视频集
                this.loadEpisodes(this.form.courseId)
                // 不关闭弹框，允许继续上传视频和封面
              } else {
                this.$message.success('新增成功')
                this.episodeDialogVisible = false
                this.loadEpisodes(this.form.courseId)
              }
            } else {
              this.$message.error(res.msg || '新增失败')
            }
          }).catch(error => {
            console.error('新增视频集失败:', error)
            this.$message.error('新增失败')
          })
        }
      })
    },
    handleDeleteEpisode(row) {
      this.$modal.confirm('是否确认删除该视频集？').then(() => {
        return delEpisode(row.episodeId)
      }).then(() => {
        this.$message.success('删除成功')
        this.loadEpisodes(this.form.courseId)
      }).catch(() => {})
    },
    // ========== 动作管理方法 ==========
    loadActionsByEpisode() {
      if (!this.selectedEpisodeId) {
        this.actions = []
        return
      }
      listActionByEpisode(this.selectedEpisodeId).then(response => {
        const res = response.data || response
        if (res && (res.code === 200 || res.code === 0 || res.success)) {
          this.actions = res.data || res || []
        } else {
          this.actions = []
        }
      }).catch(() => {
        this.actions = []
      })
    },
    openActionDialog() {
      if (!this.selectedEpisodeId) {
        this.$message.warning('请先选择视频集')
        return
      }
      this.actionForm = {
        actionId: null,
        actionTitle: '',
        actionDesc: '',
        startTime: null,
        endTime: null,
        sort: 0,
        status: '0'
      }
      this.actionDialogVisible = true
    },
    handleEditAction(row) {
      this.actionForm = {
        actionId: row.actionId,
        actionTitle: row.actionTitle,
        actionDesc: row.actionDesc || '',
        startTime: row.startTime,
        endTime: row.endTime,
        sort: row.sort || 0,
        status: row.status || '0'
      }
      this.actionDialogVisible = true
    },
    submitActionForm() {
      this.$refs.actionFormRef.validate(valid => {
        if (!valid) return
        if (this.actionForm.endTime <= this.actionForm.startTime) {
          this.$message.error('结束时间必须大于开始时间')
          return
        }
        const payload = {
          episodeId: this.selectedEpisodeId,
          actionTitle: this.actionForm.actionTitle,
          actionDesc: this.actionForm.actionDesc,
          startTime: this.actionForm.startTime,
          endTime: this.actionForm.endTime,
          sort: this.actionForm.sort,
          status: this.actionForm.status
        }
        if (this.actionForm.actionId) {
          payload.actionId = this.actionForm.actionId
          updateAction(payload).then(response => {
            this.$message.success('更新成功')
            this.actionDialogVisible = false
            this.loadActionsByEpisode()
          })
        } else {
          createAction(payload).then(response => {
            const res = response.data || response
            if (res && (res.code === 200 || res.code === 0 || res.success)) {
              this.$message.success('新增成功')
              this.actionDialogVisible = false
              this.loadActionsByEpisode()
            } else {
              this.$message.error(res.msg || '新增失败')
            }
          })
        }
      })
    },
    handleDeleteAction(row) {
      this.$modal.confirm('是否确认删除该动作？').then(() => {
        return delAction(row.actionId)
      }).then(() => {
        this.$message.success('删除成功')
        this.loadActionsByEpisode()
      }).catch(() => {})
    }
  }
}
</script>

<style scoped>
/* 对话框内容滚动容器 */
.dialog-content-wrapper {
  max-height: 70vh;
  overflow-y: auto;
  padding-right: 10px;
}

/* 对话框内容区域 */
.dialog-content {
  padding: 10px 0;
}

/* 一级标题样式 */
.section-title {
  font-size: 18px;
  font-weight: bold;
  color: #303133;
  margin: 30px 0 20px 0;
  padding-bottom: 10px;
  border-bottom: 2px solid #e4e7ed;
}

.section-title:first-child {
  margin-top: 0;
}

/* 表单区域 */
.section-form {
  padding: 0 20px;
  margin-bottom: 20px;
}

/* 内容区域 */
.section-content {
  padding: 0 20px;
  margin-bottom: 20px;
}

.row-upload {
  display: flex;
  align-items: center;
  gap: 12px;
}
.thumb {
  width: 120px;
  height: 68px;
  object-fit: cover;
  border: 1px solid #eee;
  border-radius: 4px;
}
.preview {
  margin-top: 10px;
}
.tip {
  color: #909399;
  margin-top: 6px;
}
</style>
